package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	db := database{"shoes": 50, "socks": 5}
	//log.Fatal(http.ListenAndServe("localhost:8000",db))
	mux := http.NewServeMux()
	mux.Handle("/list", http.HandlerFunc(db.list))
	mux.Handle("/price", http.HandlerFunc(db.price))
	log.Fatal(http.ListenAndServe("localhost:8000", mux))
}

type database map[string]dollars

type dollars float32

func (d dollars) String() string {
	return fmt.Sprintf("$%.2f", d)
}

func (db database) ServeHTTP(rsp http.ResponseWriter, req *http.Request) {
	//for item, price := range db{
	//	fmt.Fprintf(rsp,"%s:%s\n",item,price)
	//}
	switch req.URL.Path {
	case "/list":
		for item, price := range db {
			fmt.Fprintf(rsp, "%s:%s\n", item, price)
		}
	case "/price":
		item := req.URL.Query().Get("item")
		price, ok := db[item]
		if !ok {
			rsp.WriteHeader(http.StatusNotFound)
			fmt.Fprintf(rsp, "no such item : %q\n", item)
			return
		}
		fmt.Fprintf(rsp, "%s:%s\n", item, price)
	default:
		rsp.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(rsp, "no such page: %s\n", req.URL)
	}
}

func (db database) list(rsp http.ResponseWriter, req *http.Request) {
	for item, price := range db {
		fmt.Fprintf(rsp, "%s:%s\n", item, price)
	}
}

func (db database) price(rsp http.ResponseWriter, req *http.Request) {
	item := req.URL.Query().Get("item")
	price, ok := db[item]
	if !ok {
		rsp.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(rsp, "no such item : %q\n", item)
		return
	}
	fmt.Fprintf(rsp, "%s:%s\n", item, price)
}
